<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\base\Exception;
use yii\web\HttpException;
use yii\web\ForbiddenHttpException;
use yii\helpers\Url;
use yii\helpers\Json;
use yii\data\ActiveDataProvider;
use dosamigos\qrcode\QrCode;
use app\models\MakeklineForm;
use app\models\KlineConfigForm;
use app\models\CongzhiMoneyForm;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\NeaZoushi;
use app\models\FenhongForm;
use app\models\SysConfig;
use app\models\TuijianForm;
use app\models\SeventuijianForm;
use app\models\LindaoForm;
use app\models\NoticeForm;
use app\models\Notice;
use app\models\ReguserForm;
use app\models\Member;
use app\models\MemberActivity;
use app\models\ChangepwForm;
use app\models\CanloginForm;
use app\models\SysconfigForm;
use app\models\UploadForm;
use app\models\SmsLog;
use app\models\ZijinhuzhuanForm;
use app\models\CongzhiChannelForm;
use app\models\CongzhialipayForm;
use app\models\SendmessageForm;
use app\models\Message;
use app\models\EditprofileForm;
use app\models\ChargeCashDeal;
use app\models\CongzhifanhuanForm;
use app\models\ChannelsetForm;
use app\models\SxyconfigForm;
use app\models\WeixinconfigForm;
use app\models\AlipayconfigForm;
use app\models\TixianForm;
use app\models\UpdatememberForm;
use app\models\ZijinhuzhuansetForm;
use app\models\ForgetpwForm;
use app\models\OrdernoAutogene;

use Payment\Common\PayException;
use Payment\Client\Charge;
use Payment\Config;

class SiteController extends Controller
{
   public $curUserIsAdmin=false;
   public $sysConfig;
   public $user;
   public function beforeAction($action)
    {
      $this->sysConfig=SysConfig::getSysConfig();
      $this->curUserIsAdmin = SysConfig::curUserIsAdmin($this->sysConfig);
      if(!Yii::$app->user->isGuest){
        $this->user=Member::findOne(Yii::$app->user->getId());
      }
      //检查是否允许登录
      return parent::beforeAction($action);
    }

    /**
     * @inheritdoc  访问控制 ACF
     */
    public function behaviors()
    {
        return [
            //认证用户行为
            'access' => [
                'class' => AccessControl::className(),
                //only 选项指明 ACF 应当只 对 logout 方法起作用
                'only' => ['logout','messages','users','neazoushi','msgdetail','editprofile','notice',
                            'wizardcongzhi','sysconfig','lindao','neacount','usdcount','zijinhuzhuan','viewzijinhuzhuan',
                            'changepw','tixianreg','user','editprofile','generatepushtjm','regprove','congzhi2','zijinhuzhuanconfig',
                            'sxyconfig'
                          ],
                'ruleConfig'=>[
                  'class' => 'app\accessrules\neaaccessrule',
                  'denyCallback'=>function($rule, $action){
                    if($rule->roles[0]==='#'){
                      Yii::$app->user->logout();
                      $sysconfig=SysConfig::getSysConfig();
                      $tip=[
                        0=>'系统正在维护中，请稍后访问...',
                        1=>'系统正在结算收益，请稍后访问...'
                      ];
                      $tiptitle=[
                        0=>'系统正在维护',
                        1=>'系统正在结算'
                      ];


                      $message='';
                      $name='';
                      if(!is_null($sysconfig->forbid_tip)){
                        if(0==$sysconfig->forbid_tip){
                          $message=$tip[0];
                          $name=$tiptitle[0];
                        }else if(1==$sysconfig->forbid_tip){
                          $message=$tip[1];
                          $name=$tiptitle[1];
                        }else{
                          $message=$tip[0];
                          $name=$tiptitle[0];
                        };
                      }else{
                        $message=$tip[0];
                        $name=$tiptitle[0];
                      }
                      echo $this->render('error',['name'=>$name,'message'=>$message,'exception'=>'']);
                    }
                  }
                ],
                'rules' => [
                  [
                      'allow' => false,
                      //@ 是一个特殊标识， 代表”已认证用户”。
                      //? 是另一个特殊的标识，代表”访客用户”
                      //# 代表一个不被nea允许的用户
                      'roles' => ['#'],
                  ],
                    // 允许认证用户
                    [
                        'allow' => true,
                        //@ 是一个特殊标识， 代表”已认证用户”。
                        //? 是另一个特殊的标识，代表”访客用户”
                        'roles' => ['@'],
                    ],


                ],
            ],
            //指定该规则用于匹配哪种请求方法（例如GET，POST）。 这里的匹配大小写不敏感
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post','get'],
                ],
            ],

        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }


    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        //unset($this->layout);
        //$this->layout=null;
        if (Yii::$app->user->isGuest) {
            return $this->redirect(Url::toRoute('site/login'));
        }
        $this->layout='dashboard';
        return $this->redirect(Url::toRoute('site/neazoushi'));
    }
    /**
     * 设置充值通道
     *
     * @return string
     */
    public function actionChannelconfig()
    {
        $this->layout='dashboard';
        $model = new ChannelsetForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            if(!SysConfig::updatePayChannel($model)){
              $model->addError("", '充值通道设置失败');
            }

          }
          return $this->render('channelconfig',['model'=>$model,"tip"=>true]);
        }else{
          $sysconfig = SysConfig::getSysConfig();
          if(isset($sysconfig)){
            $arr=explode(',',$sysconfig->pay_channel);
            if(count($arr)!=3){
              $arr[0]=0;
              $arr[1]=0;
              $arr[2]=0;
            }

            $model->sxy_checked=$arr[0];
            $model->alipay_checked=$arr[1];
            $model->weixin_checked = $arr[2];
          }
          return $this->render('channelconfig',['model'=>$model]);
        }
    }

    /**
     * 配置首信易
     *
     * @return string
     */
    public function actionSxyconfig()
    {
        $this->layout='dashboard';
        $model = new SxyconfigForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            if(!SysConfig::updateSxyConfig($model)){
              $model->addError("", '首信易支付设置失败');
            }

          }
          return $this->render('sxyconfig',['model'=>$model,"tip"=>true]);
        }else{
          $sysconfig = SysConfig::getSysConfig();
          if(isset($sysconfig)){
            $model->businessid=$sysconfig->sxy_businessid;
            $model->key=$sysconfig->sxy_key;
          }
          return $this->render('sxyconfig',['model'=>$model]);
        }
    }


    /**
     * 配置微信支付
     *
     * @return string
     */
    public function actionWeixinconfig()
    {
        $this->layout='dashboard';
        $model = new WeixinconfigForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            $model->certfile = UploadedFile::getInstance($model, 'certfile');
            $cert='';
            if ($model->certfile) {
              if($model->certfile->extension!=''){
                $cert='cert/weixincert.' . $model->certfile->extension;
              }else{
                $cert='cert/weixincert';
              }

              $model->certfile->saveAs($cert);
              $model->cert=$cert;
            }
            if(!SysConfig::updateWeixinConfig($model)){
              $model->addError("", '微信支付设置失败');
            }

          }else{
            $model->addError("", '参数错误');
          }
          return $this->render('weixinconfig',['model'=>$model,"tip"=>true]);
        }else{
          $sysconfig = SysConfig::getSysConfig();
          if(isset($sysconfig)){
            $model->businessid=$sysconfig->weixin_businessid;
            $model->appid=$sysconfig->weixin_appid;
            $model->appsecret = $sysconfig->weixin_appsecret;
            $model->ipakey =$sysconfig->weixin_ipakey;
            $model->cert = $sysconfig->weixin_cert;
            $model->certfile = $sysconfig->weixin_cert;
            $arr = explode(',',$sysconfig->pay_channel);
            if(count($arr)==3){
              $model->disable= ($arr[2]==1)?0:1;
            }
            else{
              $model->disable= 1;
            }

          }
          return $this->render('weixinconfig',['model'=>$model]);
        }
    }
    /**
     * 配置支付宝支付
     *
     * @return string
     */
    public function actionAlipayconfig()
    {
        $this->layout='dashboard';
        $model = new AlipayconfigForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())) {
            $model->qrcodefile = UploadedFile::getInstance($model, 'qrcodefile');
            if($model->validate()){
              $qrcode = '';
              if ($model->qrcodefile) {
                $qrcode='uploads/qrcode.' . $model->qrcodefile->extension;
                $model->qrcodefile->saveAs($qrcode);
                $model->qrcode=$qrcode;
              }
              if(!SysConfig::updateAlipayConfig($model)){
                $model->addError("", '支付宝支付设置失败');
              }
            }
          }

          return $this->render('alipayconfig',['model'=>$model,"tip"=>true]);

        }else{
          $sysconfig = SysConfig::getSysConfig();
          if(isset($sysconfig)){
            $model->count=$sysconfig->alipay_count;
            $model->qrcode=$sysconfig->alipay_qrcode;
            $arr = explode(',',$sysconfig->pay_channel);
            if(count($arr)==3){
              $model->disable= ($arr[1]==1)?0:1;
            }
            else{
              $model->disable= 1;
            }
          }
          return $this->render('alipayconfig',['model'=>$model]);
        }
    }

    public function actionQrcode() {
        $qrid=Yii::$app->request->get('qrid');
        $deal = ChargeCashDeal::findOne($qrid);
        if(!is_null($deal)){
          if($deal->channel==ChargeCashDeal::CHANNEL_ALIPAY){
        //    header('Content-Type: image/jpeg');
            //判断图片类型
            /*$file=fopen($this->sysConfig->alipay_qrcode,'rb');
            $bin = fread($file,2);//读开始的2个字节
            fclose($file);
            $strInfo=@unpack('C2chars',$bin);
            $typeCode=intval($strInfo['chars1'].$strInfo['chars2']);
            $fileType='';
            switch($typeCode){
              case 7790:
                $fileType = 'exe';break;
              case 7784:
                $fileType = 'midi';break;
              case 8297:
                $fileType = 'rar';break;
              case 255216:
                $fileType = 'jpg';break;
              case 7173:
                $fileType = 'gif';break;
              case 6677:
                $fileType = 'bmp';break;
              case 13780:
                $fileType = 'png';break;
              default:
                $fileType = 'unknown';
            }*/
            if(file_exists($this->sysConfig->alipay_qrcode)){
              $info=@getimagesize($this->sysConfig->alipay_qrcode);
              $ext = image_type_to_extension($info['2']);
              switch($ext){
                case '.jpeg':
                  $img = @imagecreatefromjpeg($this->sysConfig->alipay_qrcode);
                  if($img){
                    header('Content-Type: image/jpeg');
                    imagejpeg($img);
                  }
                  break;
                case '.gif':
                  $img = @imagecreatefromgif($this->sysConfig->alipay_qrcode);
                  if($img){
                    header('Content-Type: image/gif');
                    imagegif($img);
                  }
                  break;
                case '.png':
                  $img = @imagecreatefrompng($this->sysConfig->alipay_qrcode);
                  if($img){
                    header('Content-Type: image/png');
                    imagepng($img);
                  }
                  break;
                default:
              }

            }


          }else{
            return QrCode::png($deal->orderlink);
          }
        }
    }

    public function actionSendmessage()
    {
      if (Yii::$app->request->isAjax) {
        $receiver=Yii::$app->request->get('receiver');
        $content=Yii::$app->request->get('content');
        if(is_null($receiver)||is_null($content)||
        strlen($receiver)<1||strlen($receiver)>30||
        strlen($content)<1||strlen($content)>65536
        ){
          echo Json::encode(array('errcode'=>2,'errmsg'=>'参数错误，发送失败。'));
        }else{
          if(Message::addAndSendMessage($content,$receiver,false)){
            echo Json::encode(array('errcode'=>0,'errmsg'=>'发送成功。'));
          }else{
            echo Json::encode(array('errcode'=>1,'errmsg'=>'发送失败。'));
          }
        }
      }
    }

    public function actionForbidusertipajax()
    {
      if (Yii::$app->request->isAjax) {
        $mode=Yii::$app->request->get('mode');
        if(Sysconfig::updateForbidUserTip($mode))
        {
            echo Json::encode(array('errcode'=>0,'errmsg'=>'设置禁止登录提示成功。'));
        }else{
            echo Json::encode(array('errcode'=>1,'errmsg'=>'设置禁止登录提示失败。'));
        }
      }
    }

    /**
     * ajax获取消息内容，有可能同时设置消息为已读
     *
     * @return string
     */
    public function actionGetmsgcontent()
    {
      if (Yii::$app->request->isAjax) {
        $msgid=Yii::$app->request->get('msgid');
        $is_set_readed = Yii::$app->request->get('issetreaded');
        if(is_null($msgid)){
          echo Json::encode(array('errcode'=>1,'errmsg'=>'参数错误。'));
        }else{
          if(!is_null($is_set_readed)&&$is_set_readed==1){
            $content = Message::getMessageContent($msgid,true);
          }else{
            $content = Message::getMessageContent($msgid,false);
          }

          if(is_null($content)){
            echo Json::encode(array('errcode'=>2,'errmsg'=>'消息获取失败。'));
          }else{
            echo Json::encode(array('errcode'=>0,'errmsg'=>$content));
          }
        }
      }
    }

    public function actionGetmsgsender()
    {
      if (Yii::$app->request->isAjax) {
        $msgid=Yii::$app->request->get('msgid');
        if(is_null($msgid)){
          echo Json::encode(array('errcode'=>1,'errmsg'=>'参数错误。'));
        }else{
          $sender = Message::getMessageSender($msgid);
          if(is_null($sender)){
            echo Json::encode(array('errcode'=>2,'errmsg'=>'消息发送者获取失败。'));
          }else{
            echo Json::encode(array('errcode'=>0,'errmsg'=>$sender));
          }
        }
      }
    }
    public function actionMsgdetail()
    {
      $this->layout='dashboard';
        $msgid=Yii::$app->request->get('msgid');
        $model=Message::findOne($msgid);
        return $this->render('msgdetail',['model'=>$model]);


    }
    public function actionDelmsg()
    {
      if (Yii::$app->request->isAjax) {
        $keys=Yii::$app->request->get('keys');
        $activebox=Yii::$app->request->get('activebox');
        if(is_null($keys)||is_null($activebox)){
          echo Json::encode(array('errcode'=>1,'errmsg'=>'参数错误。'));
        }else{
          if(!Message::delMsg($keys,$activebox)){
            echo Json::encode(array('errcode'=>2,'errmsg'=>'删除失败。'));
          }else{
            echo Json::encode(array('errcode'=>0,'errmsg'=>"删除成功。"));
          }
        }
      }
    }
    public function actionDelnotice()
    {
      if (Yii::$app->request->isAjax) {
        $keys=Yii::$app->request->get('keys');
        if(is_null($keys)){
          echo Json::encode(array('errcode'=>1,'errmsg'=>'参数错误。'));
        }else{
          if(!Notice::delNotice($keys)){
            echo Json::encode(array('errcode'=>2,'errmsg'=>'删除失败。'));
          }else{
            echo Json::encode(array('errcode'=>0,'errmsg'=>"删除成功。"));
          }
        }
      }
    }
    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if(Yii::$app->request->isPost)
        {
          if(isset($_POST['login-submit'])){
            if ($model->load(Yii::$app->request->post()) && $model->login()) {

              return $this->goHome();
            }
          }else if(isset($_POST['resetpw-submit'])){
            if ($model->load(Yii::$app->request->post())) {
              return $this->redirect(Url::toRoute(['site/resetpw','username'=>$model->username]));
            }else{
              return $this->render('login', [
                  'model' => $model,
              ]);
            }
          }
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionResetpw()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        if(Yii::$app->request->isAjax){
          $model=new ForgetpwForm();
          if($model->load(Yii::$app->request->post())) {
            $result=\yii\bootstrap\ActiveForm::validate($model);
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;//设置返回客户端的结果使用json格式
            //将验证结果返回客户端
            return $result;
          }
          return ;
        }else if(Yii::$app->request->isPost){
          $model=new ForgetpwForm();
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            if(!Member::changePW($model->name,$model->pw)){
              $model->addError('','重设密码失败。');
            }
          }
          return $this->render('resetpw', [
              'model' => $model,
              'tip'=>true
          ]);

        }else{
          if(is_null(Yii::$app->request->get('username'))){
            return $this->redirect(Url::toRoute('site/login'));
          }
          //忘记密码
          $model=new ForgetpwForm();
          $model->name=Yii::$app->request->get('username');
          return $this->render('resetpw', [
              'model' => $model,
          ]);
        }


    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionAdminlogin()
    {

        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        $model = new LoginForm();
        if(Yii::$app->request->isPost)
        {
          if(isset($_POST['login-submit'])){
            if ($model->load(Yii::$app->request->post()) && $model->login()) {
              if(!SysConfig::curUserIsAdmin($this->sysConfig)){

                Yii::$app->user->logout();
                $model->addError('','非管理员不能经此登录，请转到<br><a href="'.Url::toRoute('site/login').'">普通用户登录页面</a>');
                return $this->render('adminlogin', [
                    'model' => $model,
                    'tip'=>true
                ]);
              }
              return $this->goHome();
                //return $this->goBack();
            }
          }else if(isset($_POST['resetpw-submit'])){
            if ($model->load(Yii::$app->request->post())) {
              return $this->redirect(Url::toRoute(['site/adminresetpw','username'=>$model->username]));
            }else{
              return $this->render('adminlogin', [
                  'model' => $model,
              ]);
            }
          }



        }
        return $this->render('adminlogin', [
            'model' => $model,
        ]);
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionAdminresetpw()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        if(Yii::$app->request->isAjax){
          $model=new ForgetpwForm();
          if($model->load(Yii::$app->request->post())) {
            $result=\yii\bootstrap\ActiveForm::validate($model);
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;//设置返回客户端的结果使用json格式
            //将验证结果返回客户端
            return $result;
          }
          return ;
        }else if(Yii::$app->request->isPost){
          $model=new ForgetpwForm();
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            if(!Member::changePW($model->name,$model->pw)){
              $model->addError('','重设密码失败。');
            }
          }
          return $this->render('adminresetpw', [
              'model' => $model,
              'tip'=>true
          ]);

        }else{
          if(is_null(Yii::$app->request->get('username'))){
            return $this->redirect(Url::toRoute('site/adminlogin'));
          }
          //忘记密码
          $model=new ForgetpwForm();
          $model->name=Yii::$app->request->get('username');
          return $this->render('adminresetpw', [
              'model' => $model,
          ]);
        }


    }


    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
      $isadmin=$this->curUserIsAdmin;
      Yii::$app->user->logout();
      if($isadmin){
        return $this->redirect(url::toRoute('site/adminlogin'));
      } else{
        return $this->goHome();
      }
    }

    /**
     * Displays contact page.
     *
     * @return string
     */
    /*public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }*/

    /**
     * Displays about page.
     *
     * @return string
     */
    /*public function actionAbout()
    {
        return $this->render('about');
    }*/
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionNeazoushi()
    {
      $this->layout='dashboard';
      if (Yii::$app->request->isPost) {
        $model=NeaZoushi::findOne($_POST['NeaZoushi']['id']);
        if($model->load(Yii::$app->request->post())){
          if($model->validate()){
            if(!NeaZoushi::updateKlineitem($model)){
              $model->addError('','修改K线数据失败。');
            }
          }
        }
        return $this->render('neazoushi');
      }else{
        return $this->render('neazoushi');
      }
    }
    public function actionUsdcount()
    {
      $this->layout='dashboard';
        return $this->render('usdcount');
    }
    public function actionNeacount()
    {
        $this->layout='dashboard';
        return $this->render('neacount');
    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionFenhong()
    {
      $this->layout='dashboard';
        $model = new FenhongForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            $tr=Yii::$app->db->beginTransaction();
            try{
              //1.更新分红值
              if(!SysConfig::updateFenhong($model)){
                throw new Exception('静态分红设置失败。');
              }
              //2.执行分红
              if(($model->is_fenhong_exec)&&(!$model->is_stop_fenhong)){
                $fenhong_total=0;
                $users = Member::find()->where('status='.Member::STATUS_PROVED.' and id <> '.Yii::$app->user->getId())->all();
                foreach($users as $user){
                  if(!is_null($user)){
                    $fenhong_val=$user->nea_count*$model->fenhong_rate;
                    //放入个人账户
                    $fenhong_total += $fenhong_val;
                    //
                    //2.1 会员分红划拨
                    if(!Member::fenhong($user,$fenhong_val)){
                      throw new Exception('静态分红划拨失败。');
                    }
                    //2.2 七代奖励
                    $this->computeSeven($user,$this->sysConfig,$fenhong_val);
                    //2.3 记录会员分红活动
                    if(!MemberActivity::addActivity($user->id,MemberActivity::ACTIVITY_FENHONG,'按'.$model->fenhong_rate.'分红',$fenhong_val,$user->usd_count)){
                      throw new Exception('记录静态分红活动失败。');
                    }
                  }
                }
                //2.3 总账划拨
                /*if(!SysConfig::fenhong($fenhong_total)){
                      throw new Exception('总账分红失败。');
                }*/

              }
              //3.更新用户活动
              $tr->commit();
            }catch(Exception $e){
              $model->addError("", $e->getMessage());
              $tr->rollBack();
            }

          }
          return $this->render('fenhong',['model'=>$model,"tip"=>true]);
        }else{
          $sysconfig = SysConfig::getSysConfig();
          if(isset($sysconfig)){
            $model->fenhong_rate=$sysconfig->fenhong_rate;
            $model->is_fenhong_exec=$sysconfig->is_fenhong_exec;
            $model->is_stop_fenhong = $sysconfig->is_stop_fenhong;
          }
          return $this->render('fenhong',['model'=>$model]);
        }
    }

    public function computeSeven($user,$sysConfig,$fenhong_val)
    {
      //找用户的第一代推荐用户
      $one = Member::findByMemberName2($user->tjr);
      if(!$one){
        return;
      }
      if($one->id==$sysConfig->administrator){
        return;
      }
      //对第一代进行奖励
      $one_reward= $fenhong_val*$sysConfig->tjj_one_rate;
      //账户划拨
      Member::seven($one,$one_reward);

      //找用户的第二代推荐用户
      $two = Member::findByMemberName2($one->tjr);
      if(!$two){
        return;
      }
      if($two->id==$sysConfig->administrator){
        return;
      }
      //对第二代进行奖励
      $two_reward= $fenhong_val*$sysConfig->tjj_two_rate;
      //账户划拨
      Member::seven($two,$two_reward);

      //找用户的第三代推荐用户
      $three = Member::findByMemberName2($two->tjr);
      if(!$three){
        return;
      }
      if($three->id==$sysConfig->administrator){
        return;
      }
      //对第三代进行奖励
      $three_reward= $fenhong_val*$sysConfig->tjj_three_rate;
      //账户划拨
      Member::seven($three,$three_reward);

      //找用户的第四代推荐用户
      $four = Member::findByMemberName2($three->tjr);
      if(!$four){
        return;
      }

      if($four->id==$sysConfig->administrator){
        return;
      }
      //对第四代进行奖励
      $four_reward= $fenhong_val*$sysConfig->tjj_four_rate;
      //账户划拨
      Member::seven($four,$four_reward);

      //找用户的第五代推荐用户
      $five = Member::findByMemberName2($four->tjr);
      if(!$five){
        return;
      }
      if($five->id==$sysConfig->administrator){
        return;
      }
      //对第五代进行奖励
      $five_reward= $fenhong_val*$sysConfig->tjj_five_rate;
      //账户划拨
      Member::seven($five,$five_reward);

      //找用户的第六代推荐用户
      $six = Member::findByMemberName2($five->tjr);
      if(!$six){
        return;
      }
      if($six->id==$sysConfig->administrator){
        return;
      }
      //对第六代进行奖励
      $six_reward= $fenhong_val*$sysConfig->tjj_six_rate;
      //账户划拨
      Member::seven($six,$six_reward);

      //找用户的第七代推荐用户
      $seven = Member::findByMemberName2($six->tjr);
      if(!$seven){
        return;
      }
      if($seven->id==$sysConfig->administrator){
        return;
      }
      //对第七代进行奖励
      $seven_reward= $fenhong_val*$sysConfig->tjj_seven_rate;
      //账户划拨
      Member::seven($seven,$seven_reward);


    }

    public function actionConfigkline()
    {
        $this->layout='dashboard';
        $model = new KlineConfigForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库
            $this->sysConfig->k_min_y=$model->k_min_y;
            $this->sysConfig->k_max_y=$model->k_max_y;
            $this->sysConfig->jyrs=$model->jyrs;
            $this->sysConfig->jyl=$model->jyl;
            if(!$this->sysConfig->save()){
              $model->addError("", '修改K线图配置参数失败。');
            }
          }
          return $this->render('configkline',['model'=>$model,"tip"=>true]);
        }else{
          $model->k_min_y=$this->sysConfig->k_min_y;
          $model->k_max_y=$this->sysConfig->k_max_y;
          $model->jyrs=$this->sysConfig->jyrs;
          $model->jyl=$this->sysConfig->jyl;
          return $this->render('configkline',['model'=>$model]);
        }
    }
    /**
     * 用户进行资金互转（会员端）
     */
    public function actionZijinhuzhuan()
    {
        $this->layout='dashboard';
        $model = new ZijinhuzhuanForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库
            $tr=Yii::$app->db->beginTransaction();
            try{
              //1.添加转账记录，并标记为审核通过状态（一步到位，无需审核）
              if(!ChargeCashDeal::zijinHuzhuan($model->type,$model->money)){
                throw new Exception('插入转账记录失败。');
              }
              //2.进行用户转账划拨
              if(!Member::zijinHuzhuan(Yii::$app->user->getId(),$model->type,$model->money)){
                throw new Exception('用户转账划拨失败。');
              }
              //3.总账划拨
              /*if(!SysConfig::zijinHuzhuan($model->type,$model->money)){
                throw new Exception('总账转账划拨失败。');
              }*/

              //4.设置用户转账活动
              $member=Member::findOne(Yii::$app->user->getId());
              if(is_null($member)){
                throw new Exception('无法取得会员账户余额。');
              }
              $activetype=MemberActivity::ACTIVITY_NEA_TO_USD;
              $detail='基金账户转个人账户';
              if($model->type==ChargeCashDeal::TYPE_NEA_USD){
                $activetype=MemberActivity::ACTIVITY_NEA_TO_USD;
                $detail='基金账户转个人账户';
              }else if($model->type==ChargeCashDeal::TYPE_USD_NEA){
                $activetype=MemberActivity::ACTIVITY_USD_TO_NEA;
                $detail='个人账户转基金账户';
              }else{
                throw new Exception('转账类型异常。');
              }
              if(!MemberActivity::addActivity($member->id,$activetype,$detail.$model->money,$member->nea_count,$member->usd_count)){
                throw new Exception('添加用户提现活动失败。');
              }
              $tr->commit();
            }catch(Exception $e){
              $model->addError("money", $e->getMessage());
              $tr->rollBack();
            }
          }else{
            $model->addError("", '输入值中存在错误。');
          }
          return $this->render('zijinhuzhuan',['model'=>$model,"tip"=>true]);
        }else{
          return $this->render('zijinhuzhuan',['model'=>$model]);
        }
    }

    /**
     * 资金互转记录（会员端）
     *
     * @return string
     */
    public function actionViewzijinhuzhuan()
    {
        $this->layout='dashboard';
        return $this->render('viewzijinhuzhuan');
    }


    /**
     * 设置充值通道
     *
     * @return string
     */
    public function actionZijinhuzhuanconfig()
    {
        $this->layout='dashboard';
        $model = new ZijinhuzhuansetForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            if(!SysConfig::updateZijinhuzhuanConfig($model)){
              $model->addError("", '资金互转设置失败');
            }
          }
          return $this->render('zijinhuzhuanconfig',['model'=>$model,"tip"=>true]);
        }else{
          $sysconfig = SysConfig::getSysConfig();
          if(isset($sysconfig)){
            $model->zijinhuzhuan_checked=$sysconfig->zijinhuzhuan;
          }
          return $this->render('zijinhuzhuanconfig',['model'=>$model]);
        }
    }


    /**
     * 充值向导反馈.要求ajax返回text类型
     *
     * @return string
     */
    public function actionWizardcongzhiajax(){
      if(Yii::$app->request->isAjax){
        $stepNo = Yii::$app->request->post('step_number');
        switch($stepNo){
          //设置充值通道
          case 1:
            $model = new CongzhiChannelForm;
            $model->channel=1;
            return Json::encode(array(
              'errcode'=>0,
              'errmsg'=>$this->renderAjax('_congzhichannel',['model'=>$model])
              )
            );
          //设置充值金额
          case 2:
            //充值通道提交处理
            $model = new CongzhiChannelForm;
            $model->channel=Yii::$app->request->post('channel');
            if(!$model->validate()){
              //返回到第一步
              $model->addError('','充值通道设置失败，请重新设置');
              return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>$this->renderAjax('_congzhichannel',['model'=>$model,'tip'=>true])
                )
              );
            }
            //显示第二步的内容
            $modelnext = new CongzhiMoneyForm;
            $keys=  [
                      '1'=>'网银支付',
                      '2'=>'支付宝',
                      '3'=>'微信支付'
                    ];
            $modelnext->channel_name =$keys[Yii::$app->request->post('channel')];
            $modelnext->channel = Yii::$app->request->post('channel');
            //$modelnext->channel=$model->channel;
            return Json::encode(array(
                  'errcode'=>0,
                  'errmsg'=>$this->renderAjax('_congzhimoney',['model'=>$modelnext])
            ));
          //充值验证
          case 3:
            $model = new CongzhiMoneyForm;
            $model->channel=Yii::$app->request->post('channel');
            $keys=  [
                      '1'=>'网银支付',
                      '2'=>'支付宝',
                      '3'=>'微信支付'
                    ];
            if(!is_null($model->channel)){
              $model->channel_name =$keys[$model->channel];
            }

            $model->money=Yii::$app->request->post('money');
            //$model->real_name=Yii::$app->request->post('real_name');

            if(!$model->validate()){
              //返回到第二步
              $model->addError('','充值通道设置失败，请重新设置');
              return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>$this->renderAjax('_congzhimoney',['model'=>$model,'tip'=>true])
                )
              );
            }
            return Json::encode(array(
                  'errcode'=>0,
                  'errmsg'=>$this->renderAjax('_congzhiconfirm',['model'=>$model])
            ));
            break;
          //充值扫码
          case 4:
            $keys=  [
                      '1'=>'网银支付',
                      '2'=>'支付宝',
                      '3'=>'微信支付'
                    ];
            $model = new CongzhiMoneyForm;
            $model->channel=Yii::$app->request->post('channel');
            $model->money=Yii::$app->request->post('money');
            //$model->real_name=Yii::$app->request->post('real_name');
            //require_once __DIR__ . '/../../autoload.php';

            //use Payment\Common\PayException;
            //use Payment\Client\Charge;
            //use Payment\Config;

            //date_default_timezone_set('Asia/Shanghai');

            switch($model->channel){
              //网银
              case '1':
                $today=date('Ymd');
                $orderindex = 1;
                $orderno_gene = OrdernoAutogene::find()->where(['order_date' => $today])->one();
                if($orderno_gene){
                  $orderindex = $orderno_gene->sxy_cz_max_orderno+1;
                  $orderno_gene->sxy_cz_max_orderno=$orderindex;
                  $orderno_gene->save();
                }else{
                  $orderno_gene = new OrdernoAutogene;
                  $orderno_gene->order_date=$today;
                  $orderno_gene->sxy_cz_max_orderno=1;
                  $orderindex =1;
                  $orderno_gene->save();
                }

                $orderindexstr=sprintf('%06d',$orderindex);

                //对源数据进行md5签名
                $v1_moneytype='0';
                $v2_ymd=$today;
                $v3_amount=number_format($model->money,2);
                $v4_rcvname=$this->sysConfig->sxy_businessid;
                $v5_oid=$v2_ymd.'-'.$v4_rcvname.'-'.$orderindexstr;
                $v6_mid=$this->sysConfig->sxy_businessid;
                $v7_url=$this->sysConfig->site_addr.'/pay/payeasertn';
                $src_string=$v1_moneytype.$v2_ymd.$v3_amount.$v4_rcvname.$v5_oid.$v6_mid.$v7_url;

                $MD5Key=$this->sysConfig->sxy_key;
                //win32
                exec(Yii::getAlias("@app").'/payment/payease/md5/win32/MD5Win32 "'.$src_string.'" "'.$MD5Key.'"',$MD5Result,$res);
                //linux
                //exec(Yii::getAlias("@app").'/payment/payease/md5/linux/sample "'.$src_string.'" "'.$MD5Key.'"',$MD5Result,$res);

                $sign='';
                if($res==0){
                  $sign=$MD5Result[0];
                }

                if(!ChargeCashDeal::chargeRegisterForPayease($v5_oid,$model->money)){
                  $model->addError('','无法生成订单');
                  return Json::encode(array(
                        'errcode'=>1,
                        'errmsg'=>$this->renderAjax('_congzhiconfirm',['model'=>$model,'tip'=>true])
                  ));
                }

                $deal=ChargeCashDeal::find()->where(
                  ['orderno'=>$v5_oid]
                  )->One();
                if(is_null($deal)){
                  $model->addError('','无法生成订单');
                  return Json::encode(array(
                        'errcode'=>1,
                        'errmsg'=>$this->renderAjax('_congzhiconfirm',['model'=>$model,'tip'=>true])
                  ));
                }
                $easypay=[];
                $easypay['v1_moneytype']=$v1_moneytype;
                $easypay['v2_ymd']=$v2_ymd;
                $easypay['v3_amount']=$v3_amount;
                $easypay['v4_rcvname']=$v4_rcvname;
                $easypay['v5_oid']=$v5_oid;
                $easypay['v6_mid']=$v6_mid;
                $easypay['v7_url']=$v7_url;
                $easypay['sign']=$sign;
                $model->orderno = $v5_oid;
                return Json::encode(array(
                      'errcode'=>0,
                      'errmsg'=>$this->renderAjax('_congzhipay',['model'=>$model,'deal'=>$deal,'payease'=>$easypay])
                ));
                break;
              //淘宝支付
              case '2':
                //生成支付宝充值订单号
                $model->orderno=Member::generateRandom(2).time();
                $model->channel_name=$keys[$model->channel];
                $model->orderlink='';
                //将充值登记入数据库
                $qrid=ChargeCashDeal::chargeRegisterForAlipay($model);
                if(!$qrid){
                  $model->addError('','无法生成订单');
                  return Json::encode(array(
                        'errcode'=>1,
                        'errmsg'=>$this->renderAjax('_congzhiconfirm',['model'=>$model,'tip'=>true])
                  ));
                }
                $deal=ChargeCashDeal::findOne($qrid);
                if(is_null($deal)){
                  $model->addError('','无法生成订单');
                  return Json::encode(array(
                        'errcode'=>1,
                        'errmsg'=>$this->renderAjax('_congzhiconfirm',['model'=>$model,'tip'=>true])
                  ));
                }
                return Json::encode(array(
                      'errcode'=>0,
                      'errmsg'=>$this->renderAjax('_congzhipay',['model'=>$model,'deal'=>$deal])
                ));
                break;
                //微信扫码
              case '3':
                //1.调用微信支付的统一下单接口，微信后台系统返回链接参数code_url，
                //请求url https://api.mch.weixin.qq.com/pay/unifiedorder
                //无需证书
                //请求参数
                //<appid>wx2421b1c4370ec43b</appid> $this->sysconfig->weixin_appid;
                //?<attach>支付测试</attach> ?
                //<body>贝恩资本-微信充值</body>
                //<mch_id>10000100</mch_id>  $this->sysconfig->weixin_businessid
                //?<detail><![CDATA[{ "goods_detail":[ { "goods_id":"iphone6s_16G", "wxpay_goods_id":"1001", "goods_name":"iPhone6s 16G", "quantity":1, "price":528800, "goods_category":"123456", "body":"苹果手机" }, { "goods_id":"iphone6s_32G", "wxpay_goods_id":"1002", "goods_name":"iPhone6s 32G", "quantity":1, "price":608800, "goods_category":"123789", "body":"苹果手机" } ] }]]></detail>?
                //<nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str> 使用自定义的24位随机数算法
                //<notify_url>http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php</notify_url> Url::toRoute('pay/weixinrtn')
                //？<openid>oUpF8uMuAJO_M2pxb1Q9zNjWeS6o</openid> 当是公众号支付时必填，其他情况非必填？
                //<out_trade_no>1415659990</out_trade_no> WX+TIME()+RAND(2)
                //<spbill_create_ip>14.23.150.211</spbill_create_ip>Yii::$app->request->userIP
                //<total_fee>1</total_fee> 分   $model->money*100
                //<trade_type>APP</trade_type>APP--app支付，统一下单接口trade_type的传参可参考这里
                //<sign>0CB01533B8C1EF103065174F50BCA001</sign> 方法
                //◆ 参数名ASCII码从小到大排序（字典序）；
                //◆ 如果参数的值为空不参与签名；
                //◆ 参数名区分大小写；
                //key1=value1&key2=value2…    stringA最后拼接上key【$this->sysconfig->weixin_appsecret 】得到stringSignTemp字符串&key=... 对stringSignTemp进行MD5运算，再将得到的字符串所有字符转换为大写，得到sign值signValue
                //(appsecret 应用密钥)
                try{
                $nonce_str = Member::generateRandom(24);
                $out_trade_no = 'WX'.time().Member::generateRandom(2);
                $siteip='127.0.0.1';//$_SERVER['REMOTE_ADDR'];
                $stringA='';
                $stringA.='appid=';
                $stringA.=$this->sysConfig->weixin_appid;
                $stringA.='&attach=';
                $stringA.='支付测试';
                $stringA.='&body=';
                $stringA.='贝恩资本-微信充值';
                $stringA.='&mch_id=';
                $stringA.=$this->sysConfig->weixin_businessid;
                $stringA.='&nonce_str=';
                $stringA.=$nonce_str;   //使用自定义的24位随机数算法
                $stringA.='&notify_url=';
                $stringA.=$this->sysConfig->site_addr.'/pay/weixinrtn';
                $stringA.='&out_trade_no=';
                $stringA.=$out_trade_no;
                $stringA.='&spbill_create_ip=';
                $stringA.=$siteip;
                $stringA.='&total_fee=';
                $stringA.=$model->money*100;
                $stringA.='&trade_type=';
                $stringA.='NATIVE';

                //md5计算sign
                $stringSignTemp=$stringA.'&key='.$this->sysConfig->weixin_ipakey;

                //echo $stringSignTemp;
                //echo "<br>";
                $sign = md5($stringSignTemp);
                $sign = strtoupper($sign);

                //$stringA.='&sign=';
                //$stringA.=$sign;
                $paraXml='<?xml version="1.0" encoding="UTF-8"?>';
                $paraXml.='<xml>';
                $paraXml.='<appid><![CDATA[';
                $paraXml.=$this->sysConfig->weixin_appid;
                $paraXml.=']]></appid>';
                $paraXml.='<attach><![CDATA[';
                $paraXml.='支付测试';
                $paraXml.=']]></attach>';
                $paraXml.='<body><![CDATA[';
                $paraXml.='贝恩资本-微信充值';
                $paraXml.=']]></body>';
                $paraXml.='<mch_id><![CDATA[';
                $paraXml.=$this->sysConfig->weixin_businessid;
                $paraXml.=']]></mch_id>';
                $paraXml.='<nonce_str><![CDATA[';
                $paraXml.=$nonce_str;   //使用自定义的24位随机数算法
                $paraXml.=']]></nonce_str>';
                $paraXml.='<notify_url><![CDATA[';
                $paraXml.=$this->sysConfig->site_addr.'/pay/weixinrtn';
                $paraXml.=']]></notify_url>';
                $paraXml.='<out_trade_no><![CDATA[';
                $paraXml.=$out_trade_no;
                $paraXml.=']]></out_trade_no>';
                $paraXml.='<spbill_create_ip><![CDATA[';
                $paraXml.=$siteip;
                $paraXml.=']]></spbill_create_ip>';
                $paraXml.='<total_fee><![CDATA[';
                $paraXml.=$model->money*100;
                $paraXml.=']]></total_fee>';
                $paraXml.='<trade_type><![CDATA[';
                $paraXml.='NATIVE';
                $paraXml.=']]></trade_type>';
                $paraXml.='<sign><![CDATA[';
                $paraXml.=$sign;
                $paraXml.=']]></sign>';
                $paraXml.='</xml>';
                //echo $paraXml;
                //echo '<br>';
                $ch = curl_init();
                //设置超时30s
            		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                curl_setopt($ch,CURLOPT_URL, 'https://api.mch.weixin.qq.com/pay/unifiedorder');
                //ssl验证身份
            		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
            		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
            		//设置header
            		curl_setopt($ch, CURLOPT_HEADER, FALSE);
            		//要求结果为字符串且输出到屏幕上
            		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                //post提交方式
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $paraXml);
                //运行curl
                $data = curl_exec($ch);
                //返回结果
                if($data){
                  curl_close($ch);
                } else {
                  $error = curl_errno($ch);
                  curl_close($ch);
                  throw new Exception("curl出错，错误码:$error");
                }
                //echo $data;
                if(!$data){
                  throw new Exception("予下单返回xml数据异常！");
                }

                //将XML转为array
                //libxml_disable_entity_loader()作用是设置是否禁止从外部加载XML实体，设为true就是禁止，目的是防止XML注入攻击
                libxml_disable_entity_loader(true);
                $result = json_decode(json_encode(simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

          			if(array_key_exists("return_code", $result) &&
          			 $result["return_code"] == "SUCCESS" &&
          			 array_key_exists("result_code", $result) &&
          			 $result["result_code"] == "SUCCESS"){
                   //echo "\n\n";
                   //echo $result["code_url"];

                   //生成支付宝充值订单号
                   $model->orderno=$out_trade_no;
                   $model->channel_name='微信支付';
                   $model->orderlink=$result["code_url"];
                   //将充值登记入数据库
                   $qrid=ChargeCashDeal::chargeRegisterForWeixin($model);
                   if(!$qrid){
                     throw new Exception('无法生成订单');
                   }
                   $deal=ChargeCashDeal::findOne($qrid);
                   if(is_null($deal)){
                     throw new Exception('无法生成订单');
                   }
                 }else{
                   throw new Exception('订单预处理失败');
                 }
                   return Json::encode(array(
                         'errcode'=>0,
                         'errmsg'=>$this->renderAjax('_congzhipay',['model'=>$model,'deal'=>$deal])
                   ));
                 }catch(Exception $e){
                   $model->addError('', $e->getMessage());
                   return Json::encode(array(
                         'errcode'=>1,
                         'errmsg'=>$this->renderAjax('_congzhiconfirm',['model'=>$model,'tip'=>true])
                   ));
                 }
                break;
              default:
                break;
            }
            break;
          default:
            return "";
        }
        //return "<h3>test</h3>";
        return;
      }
    }

    /*
    payease 支付前登记接口
    */
    public function actionPayeaseregajax()
    {
      if(Yii::$app->request->isAjax){
        $ordno=Yii::$app->request->get('oid');
        $amount=Yii::$app->request->get('amount');
        if(is_null($ordno)||is_null($amount)){
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>'网银充值参数错误'
          ));
        }
        if(ChargeCashDeal::chargeRegisterForPayease($ordno,$amount)){
          return Json::encode(array(
                'errcode'=>0,
                'errmsg'=>'网银充值被成功记录'
          ));
        }
      }

      return Json::encode(array(
            'errcode'=>1,
            'errmsg'=>'网银充值无法记录'
      ));
    }

    public function actionMakekline()
    {
      $this->layout='dashboard';
      $model = new MakeklineForm();
      if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())) {
            //上传文件处理
            $model->klinefile = UploadedFile::getInstance($model, 'klinefile');
            if($model->validate()){
              if ($model->klinefile) {
                //$qrcode_img='uploads/' . $model->qrcode_img_file->baseName . '.' . $model->qrcode_img_file->extension;
                if($model->klinefile->extension!='xls'){
                  $model->addError('klinefile','不能识别的文件扩展名');
                }else{
                  $newfilepath='data/k.xls';
                  $model->klinefile->saveAs($newfilepath);

                  //加载excel文件
                  //$file = Yii::getAlias("@webroot")."/data/k.xls";
                  $objReader = new \PHPExcel_Reader_Excel5();
                  $objPHPExcel = $objReader->load($newfilepath);
                  $objWorksheet = $objPHPExcel->getSheet(0);
                  $highestRow = $objWorksheet->getHighestRow();//最大行数，为数字
                  $highestColumn = $objWorksheet->getHighestColumn();//最大列数 为字母
                  $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn); //将字母变为数字

                  //清除旧数据
                  $tr = Yii::$app->db->beginTransaction();
                  try{
                    $insertData=[];
                    NeaZoushi::deleteAll();
                    $tableName = NeaZoushi::tableName();
                    $field = ['data_date', 'data_time', 'data_open', 'data_close', 'data_highest', 'data_lowest','data_amount', 'data_base', 'is_fenhong_point'];
                    $max=0;
                    $min=999999999;
                    for($row = 2;$row<=$highestRow;$row++){
                        //插入数据库
                        $highest=$objWorksheet->getCellByColumnAndRow(4,$row)->getValue();
                        if($highest>$max){
                          $max=$highest;
                        }

                        $lowest=$objWorksheet->getCellByColumnAndRow(3,$row)->getValue();
                        if($lowest<$min){
                          $min=$lowest;
                        }
                         $insertData[] = [
                           $objWorksheet->getCellByColumnAndRow(0,$row)->getFormattedValue(),
                           '09:00:00',
                           $objWorksheet->getCellByColumnAndRow(1,$row)->getFormattedValue(),
                           $objWorksheet->getCellByColumnAndRow(2,$row)->getFormattedValue(),
                           $objWorksheet->getCellByColumnAndRow(4,$row)->getFormattedValue(),
                           $objWorksheet->getCellByColumnAndRow(3,$row)->getFormattedValue(),
                           $objWorksheet->getCellByColumnAndRow(5,$row)->getFormattedValue(),
                           $objWorksheet->getCellByColumnAndRow(6,$row)->getFormattedValue(),
                           0
                         ];


                    }
                    //执行，返回值为插入成功的数目
                    $totalnum = Yii::$app->db->createCommand()->batchInsert($tableName,$field,$insertData)->execute();

                    //修改sysconfig
                    $this->sysConfig->k_min_y=round($min-0.5);
                    $this->sysConfig->k_max_y=round($max+0.5);
                    $this->sysConfig->jyrs=2130;
                    $this->sysConfig->jyl=210000;
                    if(!$this->sysConfig->save()){
                      throw new Exception('更新K线图配置参数失败');
                    }
                    $tr->commit();
                    return $this->redirect(Url::toRoute('site/editkline'));
                  }catch(Exception $e){
                    $tr->rollBack();
                  }
                }

              }
          }

          }
          return $this->render('makekline',['model'=>$model,"tip"=>true]);
      }else{
          return $this->render('makekline',['model'=>$model]);
      }
    }

    public function actionEditkline()
    {
      $this->layout='dashboard';
      $dataProvider = new ActiveDataProvider([
          'query' => NeaZoushi::find()->orderBy(['data_date'=>SORT_DESC]),
          'pagination' => [
              'pageSize' => 20,
          ],
      ]);
      return $this->render('editkline',['dataProvider'=>$dataProvider]);

    }
    public function actionEditklineitem()
    {
      $this->layout='dashboard';
      $model=NeaZoushi::findOne(Yii::$app->request->get('id'));
      if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&&$model->validate()) {
              if(!NeaZoushi::updateKlineitem($model)){
                $model->addError('','修改K线数据失败。');
              }
          }
          return $this->render('editklineitem',['model'=>$model,"tip"=>true]);
        }

      return $this->render('editklineitem',['model'=>$model]);

    }
    public function actionAddklineitem()
    {
      $this->layout='dashboard';
      $model=new NeaZoushi;
      if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&&$model->validate()) {
              if(!NeaZoushi::addKlineitem($model)){
                $model->addError('','修改K线数据失败。');
              }
          }
          return $this->render('addklineitem',['model'=>$model,"tip"=>true]);
        }

      return $this->render('addklineitem',['model'=>$model]);

    }
    public function actionDelallkline(){
      if (Yii::$app->request->isAjax) {
        if(NeaZoushi::deleteAll()){
          return Json::encode(array(
                'errcode'=>0,
                'errmsg'=>'删除成功'
          ));
        }else{
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>'删除失败'
          ));
        }

      }
    }
    public function actionDelklineitem(){
      if (Yii::$app->request->isAjax) {
        $id=Yii::$app->request->get('id');
        $model=NeaZoushi::findOne($id);
        if($model->delete()){
          return Json::encode(array(
                'errcode'=>0,
                'errmsg'=>'删除成功'
          ));
        }else{
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>'删除失败'
          ));
        }

      }
    }

    public function actionWizardcongzhi()
    {
      $this->layout='dashboard';
      //当用户选择的是支付宝模式，如果有没有完成的充值登记，
      return $this->render('wizardcongzhi');
        /*$model = new CongzhiChannelForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库
            /*if($model->channel===1){
              $this->redirect('index.php?r=site/congzhichannelone');
            }else if($model->channel===2){*/
              $this->redirect(Url::toRoute('site/congzhialipay'));
            /*}else{
              throw new HttpException(500,'不支持的充值通道。');
            }*/
          /*}
          return $this->render('congzhireg',['model'=>$model,"tip"=>true]);
        }else{
          return $this->render('congzhireg',['model'=>$model]);
        }*/
    }

    /*
    提现申请
    */
    public function actionTixianreg()
    {
      $this->layout='dashboard';
        $model = new TixianForm();
        $curuser = Member::findOne(Yii::$app->user->getId());
        if(is_null($curuser)){
            return $this->redirect(Url::toRoute('site/login'));
        }
        $model->userid=$curuser->id;
        $model->name=$curuser->name;
        $model->realname = $curuser->realname;
        $model->alipay = $curuser->alipay;
        $model->opencardbank = $curuser->opencardbank;
        $model->bankcardid = $curuser->bankcardid;
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //检查提现金额是否超限
            if(!Member::tixianJudge($model->userid,$model->money,$this->sysConfig->exchange_rate)){
                $model->addError('','提现超过限额');
            }else{
              if(ChargeCashDeal::haveTixianRegUnfinished($model->userid)){
                $model->addError('','需要等待上次提现审核完毕才能再次提现');
              }else{
                //更新到数据库
                if(!ChargeCashDeal::tixianReg($model->userid,$model->realname,$model->money)){
                  $model->addError('','提现申请失败');
                }
              }
            }

          }
          return $this->render('tixianreg',['model'=>$model,"tip"=>true]);
        }else{
          return $this->render('tixianreg',['model'=>$model]);
        }
    }
    public function actionCongzhialipay()
    {
      $this->layout='dashboard';
        $model = new CongzhialipayForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())) {
            $verifyok=$model->validate();
            if($model->alipay_user!=$this->user->alipay){
              $model->addError("alipay_user", '支付宝账户与个人资料中的不符，请重新填写。如果你需要使用与个人资料中的支付宝设置不同的账号，请联系贝恩资本官方更改。');
              $verifyok=false;
            }
            if($model->member_real_name!=$this->user->realname){
              $model->addError("member_real_name", '真实姓名与个人资料中的不符，请重新填写。');
              $verifyok=false;
            }
            if($verifyok){
              if(!ChargeCashDeal::chargeRegisterForAlipay($model)){
                $model->addError("", '充值申请提交失败。');
              }else{
                //提交成功，进入正式的充值流程跟踪
                return $this->redirect(Url::toRoute('site/congzhialipaytrace'));
              }
            }
          }
          return $this->render('congzhialipay',['model'=>$model,"tip"=>true]);
        }else{
          return $this->render('congzhialipay',['model'=>$model]);
        }
    }
    public function actionTixianchanneltwo()
    {
      $this->layout='dashboard';
        $model = new CongzhichanneltwoForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库
            /*if($model->channel===1){
              $this->redirect('index.php?r=site/congzhichannelone');
            }else if($model->channel===2){
              $this->redirect('index.php?r=site/congzhichanneltwo');
            }else{
              throw new Exception('不支持的充值通道。');
            }*/
            $this->redirect(Url::toRoute('site/tixianchanneltworesult'));
          }
          return $this->render('tixianchanneltwo',['model'=>$model,"tip"=>true]);
        }else{
          return $this->render('tixianchanneltwo',['model'=>$model]);
        }
    }
    public function actionCongzhialipaytrace()
    {
        $this->layout='dashboard';
        $model = new CongzhichanneltwoForm();
        $model->alipay_user='x';
        $model->member_real_name='fff';
        $model->money=100;
        if (Yii::$app->request->isPost) {
          //if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库
            /*if($model->channel===1){
              $this->redirect('index.php?r=site/congzhichannelone');
            }else if($model->channel===2){
              $this->redirect('index.php?r=site/congzhichanneltwo');
            }else{
              throw new Exception('不支持的充值通道。');
            }*/
            return $this->redirect(Url::toRoute('site/congzhichanneltwopay'));

        //  }
        //  var_dump($model->errors);
        //  exit;
          return $this->render('congzhichanneltwoorder',['model'=>$model,"tip"=>true]);
        }else{
          return $this->render('congzhichanneltwoorder',['model'=>$model]);
        }
    }
    public function actionTixianchanneltworesult()
    {
      $this->layout='dashboard';
        $model = new CongzhichanneltwoForm();
        $model->alipay_user='x';
        $model->member_real_name='fff';
        $model->money=100;
        if (Yii::$app->request->isPost) {
          //if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库
            /*if($model->channel===1){
              $this->redirect('index.php?r=site/congzhichannelone');
            }else if($model->channel===2){
              $this->redirect('index.php?r=site/congzhichanneltwo');
            }else{
              throw new Exception('不支持的充值通道。');
            }*/
            return $this->redirect(Url::toRoute('site/tixianchanneltworesult'));

        //  }
        //  var_dump($model->errors);
        //  exit;
          return $this->render('tixianchanneltworesult',['model'=>$model,"tip"=>true]);
        }else{
          return $this->render('tixianchanneltworesult',['model'=>$model]);
        }
    }
    public function actionCongzhichanneltwopay()
    {
      $this->layout='dashboard';
        $model = new CongzhichanneltwoForm();
        $model->alipay_user='x';
        $model->member_real_name='fff';
        $model->money=100;
        if (Yii::$app->request->isPost) {
          //if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库
            /*if($model->channel===1){
              $this->redirect('index.php?r=site/congzhichannelone');
            }else if($model->channel===2){
              $this->redirect('index.php?r=site/congzhichanneltwo');
            }else{
              throw new Exception('不支持的充值通道。');
            }*/
            return $this->redirect(Url::toRoute('site/congzhichanneltwopay'));

        //  }
        //  var_dump($model->errors);
        //  exit;
          return $this->render('congzhichanneltwopay',['model'=>$model,"tip"=>true]);
        }else{
          return $this->render('congzhichanneltwopay',['model'=>$model]);
        }
    }
    public function actionTeam()
    {
      $this->layout='dashboard';
      return $this->render('team');
    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionTuijian()
    {
      $this->layout='dashboard';
      $model = new TuijianForm();
      if (Yii::$app->request->isPost) {
        if($model->load(Yii::$app->request->post())&& $model->validate()) {
          //更新到数据库
          //$dbmodel=new SysConfig();
          if(!SysConfig::updateTuijianRate($model->rate))
          {
            $model->addError("", '设置推荐奖提成比例失败。');
          }
        }
        return $this->render('tuijian',['model'=>$model,"tip"=>true]);
      }else{
        $sysconfig = SysConfig::getSysConfig();
        if(isset($sysconfig)){
          $model->rate=$sysconfig->tjj_rate;
        }
        return $this->render('tuijian',['model'=>$model]);
      }
    }
    /**
     * 设置会员充值奖励.
     *
     * @return string
     */
    public function actionCongzhifanhuan()
    {
      $this->layout='dashboard';
      $model = new CongzhifanhuanForm();
      if (Yii::$app->request->isPost) {
        if($model->load(Yii::$app->request->post())&& $model->validate()) {
          //更新到数据库
          //$dbmodel=new SysConfig();
          if(!SysConfig::updateCongzhifanhuan($model))
          {
            $model->addError("", '设置会员充值返还奖励失败。');
          }
        }
        return $this->render('congzhifanhuan',['model'=>$model,"tip"=>true]);
      }else{
        $sysconfig = SysConfig::getSysConfig();
        if(isset($sysconfig)){
          $model->exchange_rate=$sysconfig->exchange_rate;
          $model->congzhi_reward=$sysconfig->congzhi_reward;
        }
        return $this->render('congzhifanhuan',['model'=>$model]);
      }
    }
    public function actionDownloaduserinfo()
    {
      $this->layout='';

      $objPHPExcel = new \PHPExcel();

      $letter=array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
      $dataset=Member::find()->where(['status'=>Member::STATUS_PROVED])->all();
      $attrs=[
        'name' => '会员名称',
        'reg_date' => '注册日期',
        'phone' => '手机号码',
        'realname' => '真实姓名',
        'sfzid' => '身份证号码',
        'bankcardid' => '银行卡号',
        'opencardbank' => '开户行',
        'alipay' => '支付宝账号',
      ];

      $objPHPExcel->getActiveSheet()->setCellValue("$letter[0]1",'序号');
      $j=1;
      foreach( $attrs as $key=>$value){
        $objPHPExcel->getActiveSheet()->setCellValue("$letter[$j]1",$value);
        $j++;
      }
      for($i=0;$i<count($dataset);$i++){
        $data=$dataset[$i];
        $objPHPExcel->getActiveSheet()->setCellValue("$letter[0]".($i+2),$i+1);
        $j=1;
        foreach($attrs as $key=>$value){
          $objPHPExcel->getActiveSheet()->setCellValue("$letter[$j]".($i+2),$data[$key]);
          $j++;
        }
      }

      $writer=new \PHPExcel_Writer_Excel5($objPHPExcel);
      $filename='会员信息.xls';
      $encoded_filename=urlencode($filename);
      $encoded_filename=str_replace('+','%20',$encoded_filename);
      $ua=Yii::$app->request->userAgent;
      header('Pragma:public');
      header('Expires:0');
      header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
      header('Content-Type:application/force-download');
      header('Content-Type:application/vnd.ms-execl');
      header('Content-Type:application/octet-stream');
      header('Content-Type:application/download');
      if(preg_match('/MSIE/',$ua)){
        header('Content-Disposition:attachment;filename="'.$encoded_filename.'"');
      }else if(preg_match('/Firefox/',$ua)){
        header('Content-Disposition:attachment;filename*="utf8\'\''.$filename.'"');
      }else{
        header('Content-Disposition:attachment;filename="'.$encoded_filename.'"');
      }

      header('Content-Transfer-Encoding:binary');
      $writer->save('php://output');

      exit;

      }

    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionSeventuijian()
    {
      $this->layout='dashboard';
      $model = new SeventuijianForm();
      if (Yii::$app->request->isPost) {
        if($model->load(Yii::$app->request->post())&& $model->validate()) {
          //更新到数据库
          if(!SysConfig::updateSevenTuijianRate($model))
          {
            $model->addError("", '设置推荐奖七代失败。');
          }
        }else{
          $model->addError("", '参数验证失败。');
        }
        return $this->render('seventuijian',['model'=>$model,"tip"=>true]);
      }else{
        $sysconfig = SysConfig::getSysConfig();
        if(isset($sysconfig)){
          $model->one_rate=$sysconfig->tjj_one_rate;
          $model->two_rate=$sysconfig->tjj_two_rate;
          $model->three_rate=$sysconfig->tjj_three_rate;
          $model->four_rate=$sysconfig->tjj_four_rate;
          $model->five_rate=$sysconfig->tjj_five_rate;
          $model->six_rate=$sysconfig->tjj_six_rate;
          $model->seven_rate=$sysconfig->tjj_seven_rate;
        }
        return $this->render('seventuijian',['model'=>$model]);
      }
    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionLindao()
    {
      $this->layout='dashboard';
      $model = new LindaoForm();
      if (Yii::$app->request->isPost) {
        if($model->load(Yii::$app->request->post())&& $model->validate()) {
          //更新到数据库
          if(!SysConfig::updateLindaoReward($model))
          {
            $model->addError("", '设置推荐奖七代失败。');
          }
        }else{
          $model->addError("", '参数验证失败。');
        }
        return $this->render('lindao',['model'=>$model,"tip"=>true]);
      }else{
        $sysconfig = SysConfig::getSysConfig();
        if(isset($sysconfig)){
          $model->level_one=$sysconfig->level_one;
          $model->level_one_reward=$sysconfig->level_one_reward;
          $model->level_two=$sysconfig->level_two;
          $model->level_two_reward=$sysconfig->level_two_reward;
          $model->level_three=$sysconfig->level_three;
          $model->level_three_reward=$sysconfig->level_three_reward;
          $model->is_stop_lindao = $sysconfig->is_stop_lindao;
        }
        return $this->render('lindao',['model'=>$model]);
      }
    }
    /**
     * 充值成功记录.
     *
     * @return string
     */
    public function actionCongzhiok()
    {
        $this->layout='dashboard';
        return $this->render('congzhi',['mode'=>'ok']);
    }
    /**
     * 充值失败记录.
     *
     * @return string
     */
    public function actionCongzhifail()
    {
        $this->layout='dashboard';
        return $this->render('congzhi',['mode'=>'fail']);
    }
    /**
     * 支付宝充值审核.
     *
     * @return string
     */
    public function actionCongzhiprove()
    {
      $this->layout='dashboard';
        return $this->render('congzhiprove');
    }

    /**
     * 支付宝充值审核通过/或不通过 ajax
     * pass=>1：通过
     * pass=>0：不通过
     *
     * @return string
     */
    public function actionCongzhiproveajax()
    {
      if (Yii::$app->request->isAjax) {
        $id=Yii::$app->request->get('datakey');
        $ispass=Yii::$app->request->get('pass');
        $status=ChargeCashDeal::STATUS_PROVED;
        if($ispass==1){
          $status=ChargeCashDeal::STATUS_PROVED;
        }else if($ispass==0){
          $status=ChargeCashDeal::STATUS_UNPROVED;
        }else{
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>'充值审核失败'
          ));
        }

        $tr=Yii::$app->db->beginTransaction();
        try{
          //1.修改充值记录，并标记为通过或不通过状态
          if(!ChargeCashDeal::alipayCongzhiProve($id,$status)){
            throw new Exception('充值审核失败。');
          }
          if($status==ChargeCashDeal::STATUS_PROVED){
            //2.计算实际到账金额
            $model=ChargeCashDeal::findOne($id);
            if(is_null($model)){
              throw new Exception('无效的充值申请。');
            }
            $sysconfig = SysConfig::getSysConfig();
            if(is_null($sysconfig)){
              throw new Exception('无法取得汇率和充值返回比例。');
            }

            $money=($model->money+$model->money*$sysconfig->congzhi_reward)/$sysconfig->exchange_rate;
            $realmoney = $model->money/$sysconfig->exchange_rate;
            //3.进行用户账面划拨
            if(!Member::congzhi($model->member_id,$money)){
              throw new Exception('用户充值账面划拨失败。');
            }

            //4.计算推荐奖
            if(Member::isFirstCharge($model->member_id)){
              $member = Member::findOne($model->member_id);
              if($member){
                $tjr = Member::findByMemberName2($member->tjr);
                if($tjr){
                  if($tjr->id!=$sysconfig->administrator){
                    $tuijian_reward = $model->money*$sysconfig->tjj_rate/$sysconfig->exchange_rate;
                    Member::tuijian($tjr,$tuijian_reward);
                  }
                }
              }

            }

            //4.总账划拨使用无充值奖励的金额
            /*if(!SysConfig::congzhi($realmoney)){
              throw new Exception('总账充值划拨失败。');
            }*/
            //5.设置用户充值活动
            $member=Member::findOne($model->member_id);
            if(is_null($member)){
              throw new Exception('无法取得会员账户余额。');
            }
            if(!MemberActivity::addActivity($member->id,MemberActivity::ACTIVITY_CHARGE,'充值'.$model->money,$member->nea_count,$member->usd_count)){
              throw new Exception('添加用户充值活动失败。');
            }
          }
          $tr->commit();
          return Json::encode(array(
                'errcode'=>0,
                'errmsg'=>'充值审核成功'
          ));
        }catch(Exception $e){
          $tr->rollBack();
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>$e->getMessage()
          ));
        }
        if(ChargeCashDeal::alipayCongzhiProve($id,$status)){
          return Json::encode(array(
                'errcode'=>0,
                'errmsg'=>'充值审核成功'
          ));
        }else{
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>'充值审核失败'
          ));
        }
      }
    }

    /**
     * 会员端充值记录
     *
     * @return string
     */
    public function actionCongzhi2()
    {
      $this->layout='dashboard';
        return $this->render('congzhi2');
    }


    /**
     * 删除正在审核的注册 或 审核失败的注册 ajax
     *
     * @return string
     */
    public function actionDelreguserajax()
    {
      if (Yii::$app->request->isAjax) {
        $keys=Yii::$app->request->get('keys');
        if(!Member::delRegUser($keys)){
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>'删除注册失败'
          ));
        }else{
          //删除图片
          foreach($keys as $id){
            $model=Member::findOne($id);
            if(!is_null($model)){
              $sfzimgpath = $model->tjm;//sfz/Y01ZRO3KPG1502677301.jpg
              @unlink($sfzimgpath);
            }
          }


          return Json::encode(array(
                'errcode'=>0,
                'errmsg'=>'删除注册成功'
          ));
        }
      }
    }

    /**
     * 提现成功记录.
     *
     * @return string
     */
    public function actionTixianok()
    {
        $this->layout='dashboard';
        return $this->render('tixian',['mode'=>'ok']);
    }
    /**
     * 提现失败记录.
     *
     * @return string
     */
    public function actionTixianfail()
    {
        $this->layout='dashboard';
        return $this->render('tixian',['mode'=>'fail']);
    }
    /**
     * 提现审核.
     *
     * @return string
     */
    public function actionTixianprove()
    {
      $this->layout='dashboard';
        return $this->render('tixianprove');
    }

    /**
     * 提现审核通过或不通过 ajax
     * pass=>1：通过
     * pass=>0：不通过
     *
     * @return string
     */
    public function actionTixianproveajax()
    {
      if (Yii::$app->request->isAjax) {
        $id=Yii::$app->request->get('datakey');
        $ispass=Yii::$app->request->get('pass');
        $status=ChargeCashDeal::STATUS_PROVED;
        if($ispass==1){
          $status=ChargeCashDeal::STATUS_PROVED;
        }else if($ispass==0){
          $status=ChargeCashDeal::STATUS_UNPROVED;
        }else{
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>'提现审核失败'
          ));
        }
        $tr = Yii::$app->db->beginTransaction();
        try {
          //1.设置提现审核状态
          if(!ChargeCashDeal::tixianProve($id,$status)){
            throw new Exception('设置提现状态失败。');
          }
          if($ispass==1){
            $model = ChargeCashDeal::findOne($id);
            if(is_null($model)){
              throw new Exception('提现时进行用户账户划拨失败。');
            }
            //2.进行用户账户划拨
            //进行汇率转换
            $money = $model->money/$this->sysConfig->exchange_rate;
            if(!Member::tixian($model->member_id,$money,false)){
              throw new Exception('提现时进行用户账户划拨失败。');
            }
            //3/进行总账账户划拨
            /*if(!SysConfig::tixian($money)){
              throw new Exception('提现时进行总账划拨失败。');
            }*/
            //4.更新提现次数
            $cur_tixian_count = ChargeCashDeal::totalTixianCount($model->member_id);
            //$cur_tixian_count ++;
            if(!Member::updateCurTixianCount($model->member_id,$cur_tixian_count)){
              throw new Exception('更新提现次数失败。');
            }
            //5.设置用户提现活动
            $member=Member::findOne($model->member_id);
            if(is_null($member)){
              throw new Exception('无法取得会员账户余额。');
            }
            if(!MemberActivity::addActivity($member->id,MemberActivity::ACTIVITY_CASH,'提现'.$model->money,$member->nea_count,$member->usd_count)){
              throw new Exception('添加用户提现活动失败。');
            }

          }
          $tr->commit();
          return Json::encode(array(
                'errcode'=>0,
                'errmsg'=>'提现审核成功'
          ));
        } catch (Exception $e) {
          $tr->rollBack();
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>$e->getMessage()
          ));
        }
      }
    }

    /**
     * 提现审核不通过 ajax
     *
     * @return string
     */
    public function actionTixianprovenopass()
    {
      if (Yii::$app->request->isAjax) {
        $id=Yii::$app->request->get('datakey');
        if(ChargeCashDeal::alipayTixianProve($id,ChargeCashDeal::STATUS_UNPROVED)){
          return Json::encode(array(
                'errcode'=>0,
                'errmsg'=>'提现审核成功'
          ));
        }else{
          return Json::encode(array(
                'errcode'=>1,
                'errmsg'=>'提现审核失败'
          ));
        }
      }
    }
    /**
     * 会员端提现记录.
     *
     * @return string
     */
    public function actionTixian2()
    {
        $this->layout='dashboard';
        return $this->render('tixian2');
    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionMessages()
    {
      $this->layout='dashboard';
        return $this->render('messages');
    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionNotice()
    {
      $this->layout='dashboard';
      if($this->curUserIsAdmin){
        return $this->render('noticeadmin');
      }else{
        return $this->render('notice');
      }
    }

    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionAddnotice()
    {
      $this->layout='dashboard';
        $model = new NoticeForm();
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库
            if(!Notice::addNotice($model)){
              $model->addError("", '发布失败。');
            }
          }else{
            //$model->addError("", '参数验证失败。');
          }
          return $this->render('addnotice',['model'=>$model,"tip"=>true]);
        }
        return $this->render('addnotice',['model'=>$model]);
    }

    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionUseagreement()
    {
      $sc = SysConfig::getSysConfig();

      return $this->render('useagreement',['model'=>$sc]);
    }

    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionReguser()
    {
      if(Yii::$app->user->isGuest){
        //会员端
        $model = new ReguserForm();
        if ((Yii::$app->request->isPost)||(Yii::$app->request->isAjax)) {
          if($model->load(Yii::$app->request->post())) {
            if(Yii::$app->request->isAjax){
              //使用ActiveForm的validate()方法对$model的数据进行验证
              $result=\yii\bootstrap\ActiveForm::validate($model);
              Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;//设置返回客户端的结果使用json格式
              //将验证结果返回客户端
              return $result;
            }
            if(!$model->is_agree){
              return $this->render('neazoushi');
            }

            $model->sfzimgfile = UploadedFile::getInstance($model, 'sfzimgfile');
            if($model->validate()){
              $tjcode='';//历史原因使用tjcode存储身份证照片地址
              if ($model->sfzimgfile) {
                $tjcode='sfz/'.Member::generatePushTjm() .time().'.'.$model->sfzimgfile->extension;
                $model->sfzimgfile->saveAs($tjcode);
                $model->tjcode=$tjcode;
                //更新到数据库
                $tr = Yii::$app->db->beginTransaction();
                try {
                  if(!Member::addMember($model)){
                    $model->addError("", '注册失败。');
                    throw new Exception("注册失败");
                  }
                  $tr->commit();
                } catch (Exception $e) {
                  $tr->rollBack();
                }
              }else{
                $model->addError("sfzimgfile", '请上传手持身份证照片');
                $model->addError("", '参数验证失败，请检查输入');
              }

            }else{
              $model->addError("", '参数验证失败，请检查输入');
            }

          }else{
            $model->addError("", '服务器错误。');
          }
          return $this->render('reguser',['model'=>$model,"tip"=>true]);
        }
        return $this->render('reguser',['model'=>$model]);
      }else{
        //管理员端
        $this->layout='dashboard';
        $model = new ReguserForm();
        if ((Yii::$app->request->isPost)||(Yii::$app->request->isAjax)) {
          if($model->load(Yii::$app->request->post())) {
            if(Yii::$app->request->isAjax){
              //使用ActiveForm的validate()方法对$model的数据进行验证
              $result=\yii\bootstrap\ActiveForm::validate($model);
              Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;//设置返回客户端的结果使用json格式
              //将验证结果返回客户端
              return $result;
            }
            if(!$model->is_agree){
              return $this->render('neazoushi');
            }
            $model->sfzimgfile = UploadedFile::getInstance($model, 'sfzimgfile');
            if($model->validate()){
              $tjcode='';//历史原因使用tjcode存储身份证照片地址
              if ($model->sfzimgfile) {
                $tjcode='sfz/'.Member::generatePushTjm() .time().'.'.$model->sfzimgfile->extension;
                $model->sfzimgfile->saveAs($tjcode);
                $model->tjcode=$tjcode;

                //更新到数据库
                $tr = Yii::$app->db->beginTransaction();
                try {
                  if(!Member::addMember($model)){
                    $model->addError("", '注册失败。');
                    throw new Exception("注册失败");
                  }
                  $tr->commit();
                } catch (Exception $e) {
                  $tr->rollBack();
                }

              }else{
                $model->addError("sfzimgfile", '请上传手持身份证照片');
                $model->addError("", '参数验证失败，请检查输入');
              }
            }else{
              $model->addError("", '参数验证失败，请检查输入');
            }

          }else{
            $model->addError("", '服务器错误。');
          }
          return $this->render('reguser',['model'=>$model,"tip"=>true]);
        }
        return $this->render('reguser',['model'=>$model]);
      }

    }


    public function actionRegprove()
    {
        $this->layout='dashboard';
        $dataProvider = new ActiveDataProvider([
          'query' => Member::find()->where(['status'=>[Member::STATUS_REGISTER,Member::STATUS_UNPROVED]])->orderBy(['reg_date'=>SORT_DESC]),
          'pagination' => [
              'pageSize' => 20,
          ],
        ]);
        return $this->render('regprove',['dataProvider'=>$dataProvider]);
    }

    /**
     * 注册审核
     *
     * @return string
     */
    public function actionRegproveajax()
    {
      if (Yii::$app->request->isAjax) {
        $datakey = Yii::$app->request->get('datakey');
        $pass = Yii::$app->request->get('pass');
        $tr = Yii::$app->db->beginTransaction();
        try{
          if(!Member::proveUser($datakey,$pass)){
            throw new Exception('设置用户注册状态失败。');
          }else{
            if($pass==1){
              //删除图片
              $model=Member::findOne($datakey);
              if(!is_null($model)){
                $sfzimgpath = $model->tjm;//sfz/Y01ZRO3KPG1502677301.jpg
                @unlink($sfzimgpath);
              }
              //添加活动（注册成功，初始化账户金额
              $memberid=$model->id;
              if(!MemberActivity::addActivity($memberid,MemberActivity::ACTIVITY_REG_USER,"注册会员".$model->name,0,0)){
                throw new Exception('添加用户注册活动失败。');
              }
            }

          }
          $tr->commit();
          echo Json::encode(array('errcode'=>0,'errmsg'=>'审核用户注册成功。'));
        }catch(Exception $e){
          $tr->rollBack();
          echo Json::encode(array('errcode'=>1,'errmsg'=>$e->getMessage()));
        }
      }
    }



    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionSendsms()
    {
      //$this->layout='dashboard';
      if (Yii::$app->request->isAjax) {
        $phone = Yii::$app->request->get('phone');
        $returnMsg=SmsLog::requestSms($phone,"userRegister");
        echo Json::encode(array('return-msg'=>$returnMsg));
      }

    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionUsers()
    {
      $this->layout='dashboard';

      $dataProvider = new ActiveDataProvider([
          'query' => Member::find()->where(['status'=>Member::STATUS_PROVED]),
          'pagination' => [
              'pageSize' => 20,
          ],
      ]);
        return $this->render('users',['dataProvider'=>$dataProvider]);
    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionUser()
    {
      if (Yii::$app->user->isGuest) {
          return $this->redirect(Url::toRoute('site/login'));
      }
      $this->layout='dashboard';
      $model=new UpdatememberForm;
      if(Yii::$app->request->isPost){
        if($model->load(Yii::$app->request->post())&& $model->validate()) {
          //更新到数据库
          if(!Member::updateMemberInfo($model)){
            $model->addError("", '修改会员信息失败'.print_r($model->errors,true));
          }
        }else{
            $model->addError("", '参数验证失败');
        }
        return $this->render('user',['model'=>$model,"tip"=>true]);
      }else{
        if(is_null(Yii::$app->request->get('id'))){
          $userId=Yii::$app->user->getId();
        }else{
          $userId=Yii::$app->request->get('id');
        }


        $user = Member::findOne($userId);
        $model->id=$user->id;
        $model->name=$user->name;
        $model->realname=$user->realname;
        $model->alipay=$user->alipay;
        $model->opencardbank=$user->opencardbank;
        $model->bankcardid=$user->bankcardid;
        $model->sfzid=$user->sfzid;
        $model->phone=$user->phone;

        return $this->render('user',['model'=>$model]);
      }
    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionChangepw()
    {
      $this->layout='dashboard';
      $model = new ChangepwForm();
      if (Yii::$app->request->isPost) {
        if(!$this->curUserIsAdmin){
          $model->name=$this->user->name;
        }
        if($model->load(Yii::$app->request->post())&& $model->validate()) {
          //更新到数据库
          if(!Member::changePW($model->name,$model->new_pw)){
            $model->addError("", '改密码失败。');
          }
        }else{
          $model->addError("", '参数验证失败。');
        }
        return $this->render('changepw',['model'=>$model,"tip"=>true]);
      }else if(Yii::$app->request->isAjax){
        $model->name=Yii::$app->request->get('name');
        $model->new_pw=Yii::$app->request->get('new_pw');
        //校验
        if(!$model->validate()){
          echo Json::encode(array('errcode'=>1,'errmsg'=>'参数错误。'));
          return;
        }
        //修改
        if(!Member::changePW($model->name,$model->new_pw)){
          echo Json::encode(array('errcode'=>2,'errmsg'=>'修改密码失败。'));
          return;
        }else{
          echo Json::encode(array('errcode'=>0,'errmsg'=>'修改密码成功。'));
          return;
        }
      }
      return $this->render('changepw',['model'=>$model]);
    }
    /**
     * 置会员登录权限.
     *
     * @return string
     */
    public function actionForbiduser()
    {
      $this->layout='dashboard';
      //status:0,未审批
      //status：1，审批通过
      //status：2，审批未通过
      $dataProvider = new ActiveDataProvider([
        'query' => Member::find()->where([
          'status'=>Member::STATUS_PROVED,
          ])->andWhere(['NOT',['id'=>Yii::$app->user->getId()]])->orderBy(['reg_date'=>SORT_DESC]),
        'pagination' => [
            'pageSize' => 20,
        ],
      ]);
      return $this->render('forbiduser',['dataProvider'=>$dataProvider]);
      /*$model = new CanloginForm();
      if (Yii::$app->request->isPost) {
        if($model->load(Yii::$app->request->post())&& $model->validate()) {
          //更新到数据库
          if(!Member::changeLoginright($model)){
            $model->addError("", '设置会员登录权限失败。');
          }
        }else{
          $model->addError("", '参数验证失败。');
        }
        return $this->render('forbiduser',['model'=>$model,"tip"=>true]);
      }else if(Yii::$app->request->isAjax){
        if(!$this->curUserIsAdmin){
          echo Json::encode(array('errcode'=>2,'errmsg'=>'无操作权限。'));
          return;
        }
        $model->name=Yii::$app->request->get('name');
        $model->can_login=Yii::$app->request->get('can_login');
        //不允许更改管理员本身的登录权限
        if($model->name===$this->user->name){
          echo Json::encode(array('errcode'=>2,'errmsg'=>'无操作权限。'));
          return;
        }
        if(!$model->validate()) {
          echo Json::encode(array('errcode'=>1,'errmsg'=>'参数错误。'));
          return;
        }
        //更新到数据库
        if(!Member::changeLoginright($model)){
          echo Json::encode(array('errcode'=>3,'errmsg'=>'设置会员登录权限失败。'));
          return;
        }else{
          echo Json::encode(array('errcode'=>0,'errmsg'=>'设置会员登录权限成功。'));
          return;
        }
      }
      return $this->render('forbiduser',['model'=>$model]);*/

    }
    /**
     * 置会员登录权限ajax.
     *
     * @return string
     */
    public function actionForbiduserajax()
    {
      if(Yii::$app->request->isAjax){
        $keys=Yii::$app->request->get('keys');
        $mode=Yii::$app->request->get('mode');
        if(Member::forbidUsers($keys,$mode)){
          return Json::encode(array('errcode'=>0,'errmsg'=>'设置会员登录权限成功。'));
        }else{
          return Json::encode(array('errcode'=>1,'errmsg'=>'设置会员登录权限失败。'));
        }
      }else{
        throw new HttpException(400,'非法请求');
      }
    }


    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionSysconfig()
    {
      $this->layout='dashboard';
      $model = new SysconfigForm();

      if (Yii::$app->request->isPost) {
        if($model->load(Yii::$app->request->post())) {
          //$model->qrcode_img_file = UploadedFile::getInstance($model, 'qrcode_img_file');
          $model->logo_img_file = UploadedFile::getInstance($model, 'logo_img_file');
          if($model->validate()){
            //$qrcode_img='';
            $logo_img='';
            /*if ($model->qrcode_img_file) {
              //$qrcode_img='uploads/' . $model->qrcode_img_file->baseName . '.' . $model->qrcode_img_file->extension;
              $qrcode_img='uploads/qrcode.' . $model->qrcode_img_file->extension;
              $model->qrcode_img_file->saveAs($qrcode_img);
              $model->qrcode_img=$qrcode_img;
            }*/
            if ($model->logo_img_file) {
              //$logo_img='uploads/' . $model->logo_img_file->baseName . '.' . $model->logo_img_file->extension;
              $logo_img='uploads/logo.' . $model->logo_img_file->extension;
              $logo_img_used = 'images/logo.png';
              $model->logo_img_file->saveAs($logo_img);
              copy($logo_img,$logo_img_used);
              $model->logo_img=$logo_img;
            }
            //更新到数据库
            if(!Sysconfig::updateSysSetting($model)){
              $model->addError("", '设置系统配置失败。');
            }
          }
        }
        $sysconfig = SysConfig::getSysConfig();
        //$model->qrcode_img=$sysconfig->qrcode_img;
        $model->logo_img=$sysconfig->logo_img;
        return $this->render('sysconfig',['model'=>$model,"tip"=>true]);
      }else{
        $sysconfig = SysConfig::getSysConfig();
        $model->site_name=$sysconfig->site_name;
        $model->site_addr=$sysconfig->site_addr;
        $model->site_reg_id=$sysconfig->site_reg_id;
        $model->sms_user=$sysconfig->sms_user;
        $model->sms_password=$sysconfig->sms_password;
        $model->useagreement = $sysconfig->useagreement;
        $model->logo_img=$sysconfig->logo_img;


        return $this->render('sysconfig',['model'=>$model]);
      }
    }
    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionEditprofile()
    {
      $this->layout='dashboard';
        $model = new EditprofileForm();
        //如果是超级管理员，可以指定用户ID,否则使用当前用户ID
        if (Yii::$app->request->isPost) {
          if($model->load(Yii::$app->request->post())&& $model->validate()) {
            //更新到数据库

            $memberid=Yii::$app->user->getId();
            if(!Member::changeProfile($memberid,
            $model->realname,$model->sfzid,$model->bankcardid,$model->opencardbank,$model->alipay)){
              $model->addError("", '修改用户信息失败。');
            }
          }
          return $this->render('editprofile',['model'=>$model,"tip"=>true]);
        }else{
          $model->name=$this->user->name;
          $model->realname=$this->user->realname;
          $model->sfzid=$this->user->sfzid;
          $model->bankcardid=$this->user->bankcardid;
          $model->opencardbank=$this->user->opencardbank;
          $model->alipay=$this->user->alipay;
          return $this->render('editprofile',['model'=>$model]);
        }
    }
    public function actionUpload()
    {
      $this->layout='dashboard';
            $model = new UploadForm();

            if (Yii::$app->request->isPost) {
                $model->file = UploadedFile::getInstance($model, 'file');

                if ($model->file && $model->validate()) {
                    $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
                }
            }

            return $this->render('upload', ['model' => $model]);
    }
    public function actionGeneratepushtjm(){
      if(Yii::$app->user->isGuest){
        return $this->redirect(Url::toRoute('site/login'));
      }
      $this->layout='dashboard';
      $model = Member::requestPushTjm();
      return $this->render('generatepushtjm',['model' => $model]);
    }


    public function actionTest()
    {
      $this->layout='dashboard';
      $this->layout="test";
      return $this->render("test");
    }
}
